<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="20%"
    :before-close="handleClose"
  >
    <div v-loading="loading" element-loading-text="菜单加载中...">
      <el-tree
        :data="meuList"
        show-checkbox
        node-key="id"
        ref="treeMenuRef"
        default-expand-all
        :props="defaultProps"
        @check="handleCheckChange"
        :default-checked-keys="defaultChecked"
      />
    </div>
    <template #footer>
      <div style="display: flex; justify-content: center">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit" :loading="btnLoading">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { listApi } from "@/plugins/api/system/menu";
import { authReadApi, authSaveApi } from "@/plugins/api/system/role";
const defaultProps = {
  label: "title",
  children: "sub",
  value: "id",
};
let dialogVisible = ref(false);
function handleClose(done) {
  // dialogVisible.value = false;
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
}
let title = ref("角色授权");
let meuList = ref([]);
let info = ref({});
let defaultChecked = ref([]);
function initFun(row) {
  getTree().then(() => {
    getNode();
  });
  info.value = Object.assign({}, row);
  checkList.value = [];
  defaultChecked.value = [];
  dialogVisible.value = true;
}
const emit = defineEmits(["refreshList"]);
let btnLoading = ref(false);
function submit() {
  btnLoading.value = true;
  authSaveApi({
    id: info.value.id,
    nodes: checkList.value.join(","),
  })
    .then(() => {
      ElMessage.success("设置成功！");
      emit("refreshList");
      btnLoading.value = false;
      dialogVisible.value = false;
    })
    .catch(() => {
      btnLoading.value = false;
    });
}
let loading = ref(false);
function getTree() {
  return new Promise((resolve, reject) => {
    loading.value = true;
    listApi()
      .then((data) => {
        meuList.value = data;
        resolve();
        loading.value = false;
      })
      .catch(() => {
        loading.value = false;
      });
  });
}
// 获取节点
function getNode() {
  loading.value = true;
  authReadApi({
    id: info.value.id,
  })
    .then((data) => {
      let list = data.nodes.map((ele) => {
        return parseInt(ele);
      });
      defaultChecked.value = [].concat(list);

      checkList.value = [].concat(list);
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}
// 选择数据
let checkList = ref([]);
function handleCheckChange(data, checked) {
  checkList.value = checked.checkedKeys.map((e) => e);
}

defineExpose({
  initFun,
});
</script>
<style scoped lang="scss"></style>
